#include "py32f0xx.h"
#include "PY32_Config.h"
#include "typedef.h"

#define HSE_EN      0   // 002B 的 HSE不是晶振
#define SYSCLK_SW   0
#define AHBCLK_DIV  0   // HCLK_DIV HPRE
#define APBCLK_DIV  0   // PCLK_DIV PPRE
#define MCO_SEL     0
#define MCO_DIV     0   // MCOPRE

void SystemClock_Config(void)
{
    RCC->CR = (1 << 8) | (HSI_DIV << 11) | (HSE_EN << 18);
#if _LPTIM_CLK_SOURCE == 1
    RCC->CSR = (1 << 0);    // 使能 LSI
    while((RCC->CSR & (1 << 1)) == 0); // 等待 LSI 稳定, 约 150us
#endif

#if _LPTIM_CLK_SOURCE == 3
    RCC->BDCR = (1 << 0);   // 使能 LSE
    // LSE的稳定时间长达 3 秒 ,需要在应用中判断.
#endif
    // RCC->CFGR = (SYSCLK_SW << 0) | (AHBCLK_DIV << 8) | (APBCLK_DIV << 12) | (MCO_SEL << 24) | (MCO_DIV << 28);
}

void EnablePeriphClk(void)
{
    __IO uint32_t tmpreg; 

    RCC->AHBENR = RCC_AHB_PERIPH_CLKEN;
    RCC->APBENR1 = RCC_APB1_PERIPH_CLKEN;
    RCC->APBENR2 = RCC_APB2_PERIPH_CLKEN;
    RCC->IOPENR = RCC_IOP_PERIPH_CLKEN;

    /* Delay after an RCC peripheral clock enabling */
    tmpreg = READ_BIT(RCC->APBENR2, RCC_APBENR2_ADCEN);
    UNUSED(tmpreg); 
}
